<template>
  <div class="py-10 px-5 overflow-y-scroll">
    <div class="border-blue-700 border-1 rounded-lg p-4 relative mb-10">
      <h5 class="absolute -top-12px left-2 z-10 border-1 rounded-sm border-blue-700 bg-white px-2">运算规则</h5>
      <div class="mt-2 flex items-center">
        <a-radio-group v-model:value="math_type" button-style="solid">
          <a-radio-button :value="math.value" :key="math.value" v-for="math in math_type_arrays">{{
            math.label
          }}</a-radio-button>
        </a-radio-group>
        <div class="pl-4">
          <a-tooltip>
            <template #title>开启答案</template>
            <a-switch checked-children="开" un-checked-children="关" v-model:checked="is_solution" />
          </a-tooltip>
        </div>
      </div>
      <div class="mt-2">
        <a-alert
          message="开启生成答案（答案文件与试题文件的差别在于生成的word文档名称是否带“答案”后缀）"
          type="info"
          show-icon
        />
      </div>
    </div>
    <div class="border-blue-700 border-1 rounded-lg p-4 relative mb-10">
      <h5 class="absolute -top-12px left-2 z-10 border-1 rounded-sm border-blue-700 bg-white px-2">选择目录</h5>
      <div class="mt-2 flex items-center f-input">
        <h5 class="mb-0">选择word保存的路径：</h5>
        <a-input-search
          v-model:value="folder_path"
          placeholder="点击按钮选择路径，保存生成后的word文档"
          @search="useOnChooseFolderPath"
        >
          <template #enterButton>
            <a-button>选择目录</a-button>
          </template>
        </a-input-search>
      </div>
    </div>
    <div class="border-blue-700 border-1 rounded-lg p-4 relative">
      <h5 class="absolute -top-12px left-2 z-10 border-1 rounded-sm border-blue-700 bg-white px-2">
        题目数量，题目生成样式
      </h5>
      <div class="mt-2 flex items-center">
        <span>生成题目：</span>
        <a-input-number
          :max="150"
          @change="useChangeOverMaxTips"
          :min="0"
          :formatter="(value) => `${value}道题`"
          v-model:value="math_count"
          style="width: 100px"
        ></a-input-number>
        <span class="ml-4">快速生成：</span>
        <a-select v-model:value="math_count" show-search style="width: 130px" :options="math_count_options"></a-select>
        <span class="ml-4 mr-2">生成</span>
        <a-input-number :min="0" v-model:value="math_over_count" style="width: 100px"></a-input-number>
        <span class="ml-2">以内</span>
        <span class="ml-4 mr-2">每行</span>
        <a-input-number :min="0" v-model:value="math_count_line" style="width: 100px"></a-input-number>
        <span class="ml-2">道题</span>
      </div>
    </div>
    <a-button @click="useSaveDocFile" :disabled="!folder_path || math_count > 150 || !math_count" class="my-2" block type="primary" danger>
      <a-tooltip :visible="!folder_path" color="red">
        <template #title> 保存的文件路径不能为空 </template>
        <span>生成word文档</span>
      </a-tooltip>
    </a-button>
    <a-button @click="usePreviewDocFile" :disabled="math_count > 150 || !math_count" block type="primary">预览word文档（样式具体以真实文件为准）</a-button>
    <section class="h-96" v-html="p_html"></section>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, h } from 'vue';
import { ipcRenderer, shell } from 'electron';
import { notification, message } from 'ant-design-vue';

export default defineComponent({
  name: 'Home',
  setup() {
    /// 生成最大数量题目的限制数
    let m = 150;
    const _m = [];
    while (m--) {
      if (m === 0) {
        _m.unshift(150);
        break;
      }
      _m.push(m);
    }

    const _ant_message_key = 'createDocMessage';

    const state = reactive({
      /// math
      math_type: 'add', /// 是那种运算规则
      math_type_arrays: [
        {
          label: '加法运算',
          value: 'add'
        },
        {
          label: '减法运算',
          value: 'sub'
        },
        {
          label: '加减混合',
          value: 'add_sub'
        }
      ],
      is_solution: false, /// 是否带答案
      /// path
      folder_path: '',
      file_name: 'example',
      /// math count
      math_count: 20, /// 一共多少道题
      math_over_count: 100, /// 多少以内
      math_count_line: 4, /// 一行几几道
      math_count_options: _m.map((item) => {
        return {
          value: item,
          label: `${item}道题`
        };
      }),
      /// preview html
      p_html: ''
    });

    const useOnChooseFolderPath = () => {
      /// 选择目录
      ipcRenderer.send('open-file-dialog');
    };

    const useChangeOverMaxTips = (v: number) => {
      if (v > 150) {
        notification.warning({
          message: '题目数目超过最大值',
          description: h(
            'div',
            { class: 'text-[#faad14] font-bold' },
            '题目数目超过最大值，请选择适合数量的题目，最大不超过150道题.（适量练习，更加有助于学习）'
          ),
          duration: 10
        });
      }
    };

    /// 注册选择文件夹回调事件
    ipcRenderer.on('selected-directory', function (event, path) {
      state.folder_path = path;
    });

    /// 注册生成doc文件成功的回调
    ipcRenderer.on('cb-create-doc-finished', function (event, params) {
      message.success(
        {
          content: `${params.isPreview ? '缓存' : ''}文件生成成功，文件存放地址：${
            params.isPreview ? params.temp_folder_path : state.folder_path
          }`,
          key: _ant_message_key
        },
        10
      );

      /// 如果不是预览模式开启目录
      if (!params.isPreview) {
        openDocFileFolder(state.folder_path + `/${state.file_name}.docx`)
      }

      if (params.isPreview) {
        message.loading(
          {
            content: `正在预览文件`,
            key: _ant_message_key
          },
          0
        );
        event.sender.send('preview-doc');
      }
    });
    /// 注册生成doc文件失败的回调
    ipcRenderer.on('cb-create-doc-error', function (event, params) {
      message.error(
        {
          content: `文件生成失败，请联系管理员`,
          key: _ant_message_key
        },
        10
      );
    });

    ///
    ipcRenderer.on('cb-preview-doc-html-success', function (event, data) {
      state.p_html = data.html;
    });

    onMounted(() => {
      const input = document.querySelector('.f-input .ant-input');
      input?.setAttribute('disabled', 'true');
    });

    const openDocFileFolder = (folder_path: string) => {
      shell.showItemInFolder(folder_path);
    }

    const useSaveDocFile = () => {
      message.loading(
        {
          content: '正在生成docx文件，请等待~',
          key: _ant_message_key
        },
        0
      );
      ipcRenderer.send('create-doc-file', {
        isPreview: false,
        file_name: state.file_name,
        save_path: state.folder_path,
        math_type: state.math_type,
        is_solution: state.is_solution,
        math_count: state.math_count,
        math_over_count: state.math_over_count,
        math_count_line: state.math_count_line
      });
    };

    const usePreviewDocFile = () => {
      /// 预览文档
      message.loading(
        {
          content: '正在生成docx文件，请等待~',
          key: _ant_message_key
        },
        0
      );
      ipcRenderer.send('create-doc-file', {
        isPreview: true,
        file_name: state.file_name,
        save_path: state.folder_path,
        math_type: state.math_type,
        is_solution: state.is_solution,
        math_count: state.math_count,
        math_over_count: state.math_over_count,
        math_count_line: state.math_count_line
      });
    };

    return {
      ...toRefs(state),
      useOnChooseFolderPath,
      useChangeOverMaxTips,
      useSaveDocFile,
      usePreviewDocFile
    };
  }
});
</script>
<style lang="scss">
.f-input {
  .ant-input-search {
    width: 450px;
  }
}
</style>
